/*
 * $Id: gethtmls.c,v 1.4 1995/03/25 01:18:57 chris Exp $
 */

#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include "atom.h"
#include "dtd.h"
#include "html.h"
#include "entity.h"

static void dump_tree(struct block *top, FILE *outfile);
static printtext(char *str);
static printattr(char *str, char quote);
static int _WTINHTMLError(struct error *errp);

char *base;

int errs[E_CRASH + 1];

main(int ac, char *argv[])
{
    struct block *bp;
    extern FILE *yyin;
    FILE *outfile;
    char *cp;

    if (ac != 3) {
	fprintf(stderr, "Usage: %s file.html url\n", argv[0]);
	exit(1);
    }
    else {
	yyin = fopen(argv[1], "r");
	if (yyin == NULL) {
	    perror(argv[1]);
	    exit(1);
	}
	/*
	outfile = fopen(argv[3], "w");
	if (outfile == NULL) {
	    perror(argv[3]);
	    exit(2);
	}
	*/
	outfile = stdout;
    }
    HTMLSetErrorHand(_WTINHTMLError);
    HTMLParseBegin();
    HTMLParseDo(yyin);
    bp = HTMLParseEnd();
    cp = strrchr(argv[2], '/');
    ++cp;
    *cp = 0;
    base = argv[2];
    dump_tree(bp, outfile);
    HTMLFreeParseTree(bp);
 
    fprintf(stdout, "%4d %4d %4d %4d\t", errs[0], errs[1], errs[2], errs[3]);
 
    exit(0);
}

void
dump_tree(struct block *top, FILE *outfile)
{
    struct block *cur;

    /* Print out block data */
    if (top->type == TAG) {
	if (HTMLGetBAtom(top) == GetAtom("BASE")) {
	    char *cp;

	    base = HTMLGetAttr(top, "HREF");
	    cp = strrchr(base, '/');
	    if (cp) {
		*(++cp) = 0;
	    }
	}
	else if (HTMLGetBAtom(top) == GetAtom("A")) {
	    char *cp;

	    if ((cp = HTMLGetAttr(top, "HREF")) != 0) {
		if (strncmp(cp, "http:", 5) == 0) {
		    if (cp[5] != '/') {
			fprintf(outfile, "%s%s\n", base, &cp[5]);
		    }
		    else {
			fprintf(outfile, "%s\n", cp);
		    }
		}
		else if (strchr(cp, ':') == 0)
		    fprintf(outfile, "%s%s\n", base, cp);
	    }
	}
    }
    cur = top->children;
    while (cur) {
	dump_tree(cur, outfile);
	cur = cur->next_sib;
    }
}

static int
_WTINHTMLError(struct error *errp)
{
    errs[errp->severity]++;		/* Increment particular error */
    return (0);
}
